package com.sky.rabc.Interceptor;

import com.sky.rabc.common.ThreadLocalCommon;
import com.sky.rabc.enums.ServiceCode;
import com.sky.rabc.exception.ServiceException;
import com.sky.rabc.mapper.BackUserMapper;
import com.sky.rabc.po.LoginInfoPO;
import com.sky.rabc.service.impl.BackUserServiceImpl;
import com.sky.rabc.vo.LoginBackPermissionVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

@Configuration
public class UserPermissionInterceptor implements HandlerInterceptor {

    private final BackUserMapper backUserMapper;

    private final BackUserServiceImpl backUserService;

    public UserPermissionInterceptor(BackUserMapper backUserMapper, BackUserServiceImpl backUserService) {
        this.backUserMapper = backUserMapper;
        this.backUserService = backUserService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long userId = ThreadLocalCommon.getValue();
        String account = backUserMapper.getAccountById(userId);
        LoginInfoPO longinInfo = backUserMapper.getLonginInfo(account);
        //从redis获取用户的角色[]对应的权限列表
        List<LoginBackPermissionVO> permissionListByRedis = backUserService.getPermissionListByRedis(longinInfo.getRoleIds());
        // 判断权限列表中否有和请求的路径相同路径的对象
        //匹配原始URI中的第一个数字序列，并将其替换为"*"
        boolean isPathExist = permissionListByRedis.stream()
                .anyMatch(permission -> permission.getPath().equals(request.getRequestURI().replaceFirst("\\d+", "*")));
        if (!isPathExist){
            throw new ServiceException(ServiceCode.ERROR_FORBIDDEN,"禁止访问，无此操作权限");
        }
        return true;
    }
}
